<?php


namespace app\mall\command;


use app\mall\model\MallRegion;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class Region extends Command
{

    protected function configure()
    {
        $this->setName('region')
            ->setDescription('build parent_ids');
    }

    public function execute(Input $input, Output $output)
    {
        $regions = MallRegion::select();
        foreach ($regions as $region) {
            $names = $this->getMyParentId($region);
            $region->parent_names = $names;
            $rs = $region->save();
            $output->writeln($region->name . ($rs ? '更新完成' : '失败'));
        }
        return parent::execute($input, $output); // TODO: Change the autogenerated stub
    }

    public function handle()
    {

    }

    protected function getMyParentId($region, $pNames = [])
    {
        if (!$region->parent_id) {
            return $pNames;
        }

        $parent = MallRegion::find($region->parent_id);
        array_unshift($pNames, $parent->name);
        if ($parent->parent_id) {
            $pNames = $this->getMyParentId($parent, $pNames);
        }
        return $pNames;
    }

}